<?php
namespace Destroyer\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

use Destroyer\Models\DictType;
use Destroyer\Models\DictData;

class DictDataController extends Controller
{


	public function index(Request $request)
	{
		$validated = $request->validate([
			// 分页
			'page'      => 'sometimes|integer|min:1',
			'page_size' => 'sometimes|integer|between:1,100',
			// 排序
			'sorter'           => 'sometimes|array:field,direction',
			'sorter.direction' => 'sometimes|string|in:ascend,descend',
			'sorter.field'     => 'sometimes|string|in:id,created_at',
			// 筛选
			// 'filters.status'        => 'sometimes|array|size:1',
			'type_id'        => 'required|integer',
		]);

		$query = DictData::query();

		// 筛选
		if( Arr::has($validated, 'type_id') ){
			$value = Arr::get($validated, 'type_id');
			$query->where('type_id', $value);
		}

		// 排序
		$field = Arr::get($validated, 'sorter.field', 'id');
		$direction = Arr::get($validated, 'sorter.direction', 'descend');
		$query->orderBy($field, substr($direction, 0, -3));

		// 查询
		$page_size = $request->input('page_size');
		$models = $query->paginate($page_size);

		return response()->admin($models);
	}

	
	/**
	 * http://www.laravue.com/admin-api/system/dict-data/list?code=user_sex
	 */
	public function list(Request $request)
	{
		$code = $request->input('code');
		$expect = $request->input('expect');
		abort_unless($code, 404, '需要参数code');

		$type = DictType::where('code', $code)->first(['id', 'name']);

		$data = [];
		if( $type ){
			$models = DictData::where('type_id', $type->id)->get(['id', 'label', 'value']);

			if( $expect=='int' ){
				$models->each(function ($model) {
				    $model->value = (int) $model->value; // 将 'id' 字段转换为整数
				});
			}
		}

		return response()->admin($models, $type?'success':"请求成功，但是字典:{$code}不存在");
	}
}
